package jmind.core.support.locks;

import jmind.core.cache.xmemcached.Memcached;

/**
 * description: 基于memcache的分布式锁
 * @author weibo.xie
 * @date : create in 5:07 下午 2021/6/23
 */
public class XmemDistributedLock implements DistributedLock {

    public XmemDistributedLock(Memcached memcached){
        this.memcached=memcached;
    }

    private final Memcached memcached ;
    @Override
    public boolean tryLock(String key, int expire) {
        return memcached.add(key,expire,getRequestId());
    }

    /**
     * 必须先查询，再删除，保证是同一个机器同一个线程来释放锁
     * @param key
     * @return
     */
    @Override
    public boolean unlock(String key) {
        String requestId = memcached.get(key);
        if(requestId==null){
            return true;
        }
        if(requestId.equals(getRequestId())){
          return  memcached.delete(key);
        }
        return false;
    }
}